//
//  JOTabBar.m
//  网易彩票
//
//  Created by song on 15/2/7.
//  Copyright (c) 2015年 song. All rights reserved.
//

#import "JOTabBar.h"
#import "JOTabBarButton.h"

@interface JOTabBar()

@property(nonatomic,weak) UIButton *selectedButton;

@end

@implementation JOTabBar

//-(instancetype)initWithFrame:(CGRect)frame
//{
//    self =[super initWithFrame:frame];
//    
//    if(self){
//        for(int i=0 ;i< 5; i++)
//        {
//            
//            NSString *name = [NSString stringWithFormat:@"TabBar%d",i];
//            NSString *selname = [NSString stringWithFormat:@"TabBar%dSel",i];
//            [self addTabButtonWithName:name selName:selname];
//            
////            if(i==0)
////            {
////                [self buttonCLick:button];
////            }
//        }
//        
//    }
//    return self;
//}


-(void)layoutSubviews
{
    [super layoutSubviews];
    int count = self.subviews.count;
    for (int i=0; i<count; i++) {
        UIButton *button = self.subviews[i];
        button.tag = i;
        CGFloat buttonY =0;
        CGFloat buttonW =self.frame.size.width * 0.2;
        CGFloat buttonH = self.frame.size.height;
        CGFloat buttonX = i*buttonW;
        button.frame =CGRectMake(buttonX, buttonY, buttonW, buttonH);
        
    }
}

-(void)buttonCLick:(UIButton *)button
{
    
    if ([self.delegate respondsToSelector:@selector(tabBar:didSelectItemFrom:to:)]) {
        
        [self.delegate tabBar:self didSelectItemFrom:self.selectedButton.tag to:button.tag];
    }
    
    self.selectedButton.selected =NO;
    
    button.selected =YES;
    
    self.selectedButton =button;

//    self.selectedIndex = button.tag;
}

-(void)addTabButtonWithName:(NSString *)name selName:(NSString *)selname
{
 
    JOTabBarButton *button = [JOTabBarButton buttonWithType:UIButtonTypeCustom];
    [button setBackgroundImage:[UIImage imageNamed:name] forState:UIControlStateNormal];
    [button setBackgroundImage:[UIImage imageNamed:selname] forState:UIControlStateSelected];
    
    button.tag =self.subviews.count-1;
    // 设置高亮的时候，就是取消高亮状态
    button.adjustsImageWhenHighlighted =NO;
    
    [self addSubview:button];
    
    [button addTarget:self action:@selector(buttonCLick:) forControlEvents:UIControlEventTouchDown];

    if(self.subviews.count == 1)
    {
        [self buttonCLick:button];
    }
}

@end
